package com.mrper.ext.adapter.fragment;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/22.
 * 针对TabLayout的布局适配器
 */

public class SwitchFragmentStateAdapter<T extends Fragment> extends FragmentStatePagerAdapter {

    private FragmentManager fm;
    private List<T> mFragments;
    private List<String> mTitles;

    public SwitchFragmentStateAdapter(FragmentManager fm, List<T> fragments, List<String> titles) {
        super(fm);
        this.fm = fm;
        mFragments = fragments;
        mTitles = titles;
    }

    public SwitchFragmentStateAdapter(FragmentManager fm, List<T> fragments, String[] titles) {
        super(fm);
        this.fm = fm;
        mFragments = fragments;
        mTitles = new ArrayList<>();
        if(titles != null && titles.length > 0) {
            for (int i = 0; i < titles.length; i++)
                mTitles.add(titles[i]);
        }
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = mFragments.get(position);
        if (!fragment.isAdded()) {
            FragmentTransaction ft = fm.beginTransaction();
            ft.add(fragment, fragment.getClass().getSimpleName());
            ft.commit();
            /**
             * 在用FragmentTransaction.commit()方法提交FragmentTransaction对象后
             * 会在进程的主线程中，用异步的方式来执行。
             * 如果想要立即执行这个等待中的操作，就要调用这个方法（只能在主线程中调用）。
             * 要注意的是，所有的回调和相关的行为都会在这个调用中被执行完成，因此要仔细确认这个方法的调用位置。
             */
            fm.executePendingTransactions();
        }
        if (fragment.getView()!=null && fragment.getView().getParent() == null) {
            container.addView(fragment.getView()); // 为viewpager增加布局
        }
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(mFragments.get(position).getView()); // 移出viewpager两边之外的page布局
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles.get(position);
    }

}